<!-- 游戏库页面 -->
<template>
  <div class="shell" v-if="ifLoad">
    <!-- 左侧内容 -->
    <div class="left">
      <!-- 左侧上部美化内容 -->
      <div class="l-top">
        <div class="card">
          主页
        </div>
        <div class="collect">
          <Menu class="col-icon" />
        </div>
      </div>
      <!-- 左侧中部筛选分类搜索功能 -->
      <div class="l-mid">
        <div class="sel">
          <div class="s-content" @click="choseType">
            <span>{{ typeStr }}</span>
            <ArrowDownBold class="icon"/>
          </div>
          <div class="s-items" v-show="typeActive">
            <div class="s-item" v-for="(v,i) in typeOptions" :key="i" @click="selType(i)">
                <Select class="sel-icon" :class="{'icon-active': v.value}" />
                <span>{{ v.label }} ({{ typeNum[v.label] }})</span>
            </div>
          </div>
        </div>
        <div class="search">
          <Search class="icon" />
          <input v-model="search" type="text" placeholder="搜索"> 
        </div>
      </div>
      <!-- 左侧底部,显示所有自己的游戏,并且包含图标 -->
      <div class="l-bot">
        <div class="all-swit" @click="showGameTable">
          <Minus v-if="showFlag" @click.stop="showGame" class="icon" />
          <Plus v-else @click.stop="showGame" class="icon" />
          <span>全部</span>
          <el-tooltip content="打开下载目录" placement="top" style="outline:none">
            <folder-opened class="icon right-folder" @click.stop="openFolder" style="outline:none; -webkit-tap-highlight-color: transparent;"/>
          </el-tooltip>

        </div>
        <div class="items" v-if="showFlag">
          <div :title="v.name" class="s-item" v-show="(typeStr=='全部'||typeStr.includes(v.type))&&v.name.includes(search)" v-for="(v,i) in gameList" :key="i" @click="choseExe(v)">
              <Stopwatch v-if="v.icon==null" class="icon" />
              <img v-else :src="v.icon" alt="" class="icon" />
              <span>{{ v.name }}</span>
          </div>
        </div>
      </div>
      <!-- 添加游戏按钮,可以添加本地软件来管理 -->
      <div class="add-game" @click="popFlag = true">
        <Plus class="icon" />
        <span>添加游戏</span>
      </div>
      <!-- 弹出框让用户选择一般软件还是游戏类型的应用 -->
      <el-dialog v-model="popFlag" title="游戏 or 软件" width="30%">
        <el-button @click="choseFile('软件')">软件</el-button>
        <el-button type="primary" @click="choseFile('游戏')">游戏</el-button>
      </el-dialog>
    </div>
    <!-- 下载进度弹窗 -->
    <el-dialog v-model="isDownloading" title="下载进度" width="30%" :close-on-click-modal="false" :show-close="false">
      <div class="download-dialog-content">
        <div class="download-progress-text">正在下载: {{ downloadProgress }}%</div>
        <div class="download-progress-bar">
          <div class="download-progress-fill" :style="{width: downloadProgress + '%'}"></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="cancelDownload">取消下载</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 右侧内容(当选中游戏时显示) -->
    <div v-if="this.curGame" class="right">
      <!-- 如果存在封面展示封面和启动按钮,不然展示名字和启动按钮 -->
      <div class="all" :style="gameCover">
        <span v-if="curCover==null" class="tit">{{ curGame }}</span>
      </div>
      <div class="game">
        <div class="g-top">
          <CaretRight class="icon" style="cursor: pointer;" @click="openExe(curUrl)"/>
          <button @click="openExe(curUrl)">开始游戏</button>  
        </div>
        <!-- 加一个配置图标，然后"打开游戏文件夹" -->
      </div>
    </div>
    <!-- 右侧内容(刚进入页面时显示) -->
    <div v-else class="right el-right">
      <!-- 海报的形式展示所有自己加入库的游戏 -->
      <div :title="v.name" class="el-item" v-for="(v,i) in gameList" :key="i" @click="choseExe(v)">
          <img v-if="v.cover" :src="v.cover" alt="" style=""/>
          <span v-else>{{ v.name }}</span>
      </div>
    </div>
  </div>
</template>

<script>
const { shell } = require('electron');
const fs = require('fs');
const unzipper = require('unzipper');
import { ElTooltip, ElMessageBox, ElLoading } from 'element-plus'
export default {
  data(){
    return {
      externalProcess: null,
      typeOptions : [
        {
          value: true,
          label: '游戏',
        },
        {
          value:  true,
          label: '软件',
        },
      ],
      typeActive: false, 
      showFlag: true,
      search: '',
      popFlag: false,
      curGame: '',
      curUrl: '',
      curLoadUrl: '',
      curCover: '',
      popLimit: false,
      ifLoad: true,
      gameList:[],
      userGamesKey: '', // 存储用户特定的localStorage键
      isDownloading: false, // 是否正在下载
      downloadProgress: 0, // 下载进度
    }
  },
  computed:{
    typeStr(){
      var strArr = [];
      this.typeOptions.some((v)=>{ if(v.value) strArr.push(v.label); })
      if(strArr.length==0) return "全部";
      return strArr.join("和");
    },
    typeNum(){
      const num = {游戏:0,软件:0};
      this.gameList.some((v)=>{ num[v.type]++; })
      return num;
    },
    gameCover() {
      if(this.curCover==null) 
        return{
          background: 'linear-gradient(to right bottom, #999 40%, #fff 85%,#999 100%)',
          backgroundSize: 'cover'
        }
      return {
        background: `url(${this.curCover}) 0 0 no-repeat`,
        backgroundSize: 'cover'
      };
    }
  },
  methods:{
    // 初始化用户特定的游戏数据键
    initUserGamesKey() {
      const mid = this.$store.state.userInfo?.mid;
      if (mid) {
        this.userGamesKey = `games_${mid}`;
      } else {
        // 如果没有mid，使用默认键（不推荐，最好确保用户已登录）
        this.userGamesKey = 'games_default';
      }
    },
    
    // 加载用户的游戏数据
    loadUserGames() {
      const gamesData = localStorage.getItem(this.userGamesKey);
      this.gameList = gamesData ? JSON.parse(gamesData) : [];
    },
    
    // 保存用户的游戏数据
    saveUserGames() {
      localStorage.setItem(this.userGamesKey, JSON.stringify(this.gameList));
    },

    // 游戏相关函数
    choseType(){
      this.typeActive = !this.typeActive;
    },
    selType(i){
      this.typeOptions[i].value = !this.typeOptions[i].value;
    },
    // 展示游戏
    showGame(){
      this.showFlag = !this.showFlag;
    },
    showGameTable(){
      this.curGame = '';
    },
    // 选择文件
    choseFile(type){
      this.curType = type;
      this.popFlag = false;
      this.$ipc.send('open-file-dialog');
    },
    // 添加本地软件入库
    addGame(path,icon){
      var n = 0;
      // 使用反斜杠 \ 进行分割，获取文件名部分
      const parts = path.split('\\');
      // 获取最后一个部分，即文件名
      const fileNameWithExtension = parts[parts.length - 1];
      // 使用点 . 进行分割，获取文件名和扩展名
      const [fileName, fileExtension] = fileNameWithExtension.split('.');
      path = path.replace(/\\/g, '/');
      // 检查是否已存在相同路径的应用
      const exists = this.gameList.some(v => {
        return v.url == path
      });
      if (exists) {
        this.$tools.alertMsg('应用已存在','warning')
        return;
      }
      const item = {
        name: fileName,
        url: path,
        type: this.curType,
        icon: icon,
      }
      this.gameList.push(item);
      this.saveUserGames(); // 使用新的保存方法
    }, 
    // 打开游戏(软件)
    openExe(localAppPath) {
      fs.access(localAppPath, fs.constants.F_OK, (err) => {
        if (err) {
          // 检查是否已经在下载中
          if (this.isDownloading) {
            this.$tools.alertMsg("已有下载任务正在进行中，请等待当前下载完成", "warning");
            return;
          }
          
          ElMessageBox.confirm('游戏未下载，是否下载游戏', '提示', {
            confirmButtonText: '下载',
            cancelButtonText: '取消',
            type: 'warning',
          }) .then(() => {
            this.$tools.alertMsg("开始下载", "success");
            this.downloadFile(this.curLoadUrl);
          })
          .catch(() => {})
        } else {
          shell.openPath(localAppPath).then((errorMessage) => {
            if (errorMessage) {
              this.$tools.alertMsg("打开程序失败，请重试", "error");
            } else {
              this.$tools.alertMsg("成功打开程序", "success");
            }
          });
        }
      });
    },
    openFolder(){
      this.$ipc.send('open-folder');
    },
    // 选择库中的游戏
    choseExe(v){
      this.curGame = v.name;
      this.curLoadUrl =  v.dUrl;
      this.curUrl = v.url;
      this.curCover = v.cover;
    },
    // 下载游戏文件
    downloadFile(url){
      this.popLimit = true;
      this.isDownloading = true;
      this.downloadProgress = 0;
      this.$ipc.send('download-file', {
        url: url,
        savePath: 'D:/CodeRealm/app',
      });
    },
    // 取消下载
    cancelDownload() {
      this.$ipc.send('cancel-download');
      this.isDownloading = false;
    },
    // 解压游戏文件
    async unzip(url){
      const zipFilePath = url;
      const extractPath = 'D:/CodeRealm/app';
      if (!fs.existsSync(extractPath)) {
        fs.mkdirSync(extractPath);
      }
      fs.createReadStream(zipFilePath)
        .pipe(unzipper.Extract({ path: extractPath, concurrency: 5 }))
        .on('close', () => {
          console.log('解压完成');
        })
        .on('error', (err) => {
          console.error('解压失败:', err);
        });
    },
    // 获取游戏数据
    async getGames(){
      const that = this;
      await that.$axios.get("goods/findAll").then((response) => {
          if (response.status != 200) return that.$tools.alertMsg('获取数据失败，系统错误','error');
          if (response.data.data.length != 0) {
            that.$store.commit('saveGames',{gameList: response.data.data,flag:''});
          } else {
            that.$tools.alertMsg('获取游戏数据失败','error'); 
          }
      }).catch(function (error) {
          console.log(error);
      });
    },
    // 获取用户的游戏
    async getUserBox(){
      const that = this;
      await that.$axios.get('mybox/getMybox').then((response) => {
        console.log(response)
        if (response.status != 200) return that.$tools.alertMsg('系统错误', 'error');
        if (response.data.code == 200) {
          that.processGame(response.data.data);
        } else {
          that.$tools.alertMsg('获取数据失败', 'warning', 1500); 
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    // 处理游戏数据
    async processGame(data){
      for(let v of data){
        var n = 0;
        this.gameList.some((t)=>{
          if(t.name == v.gname) n=1; 
        })
        if(n==1) continue;
        const item = {
          name: v.gname,
          url: `D:/CodeRealm/app/${v.gname}/${v.gname}.exe`,
          dUrl: `http://159.75.133.177:8888/${v.path}`,
          cover: `http://159.75.133.177:8888/${v.photo}`,
          icon: v.icon,
          type: '游戏',
        }
        if(v.photo.startsWith('http')) item.cover = v.photo;
        if(v.path.startsWith('http')) item.dUrl = v.path;
        this.gameList.push(item);
      }
      this.saveUserGames(); // 使用新的保存方法
    },
    // 获取用户信息
    async getUserAll(){
      await this.getUserBox();
    }
  }, 
  async created(){
    this.initUserGamesKey(); // 初始化用户特定的键
    this.loadUserGames();    // 加载用户的游戏数据
    
    const loadOptions = { text: "加载中", background: "rgba(23,29,37,0.7)" };
    this.loadingInstance = ElLoading.service(loadOptions);
    
    // 获取用户数据
    await this.getUserAll();
    // 获取游戏数据
    await this.getGames();
    this.loadingInstance.close();
    this.ifLoad = true;

    // 移除旧的监听器
    this.$ipc.removeAllListeners('selected-file');
    this.$ipc.removeAllListeners('download-success');
    this.$ipc.removeAllListeners('download-error');
    this.$ipc.removeAllListeners('download-progress');
    this.$ipc.removeAllListeners('folder-opened');

    // 监听文件选择
    this.$ipc.on('selected-file', (event, data) => {
      console.log(data)
      this.addGame(data.path,data.icon);
    });
    // 监听文件下载
    this.$ipc.on('download-success', (event, savePath) => {
      console.log('文件已成功下载到:', savePath);
      if(this.popLimit){
        this.popLimit = false
        this.$tools.alertMsg('文件已成功下载到:'+savePath, "success",3000);
      }
      this.isDownloading = false;
      this.downloadProgress = 100;
      this.unzip(savePath);
    });
    this.$ipc.on('download-error', (event, error) => {
      // console.error('下载失败:', error);
      this.isDownloading = false;
      this.downloadProgress = 0;
      this.$tools.alertMsg( error, "error");
    });
    // 下载进度监听器
    this.$ipc.on('download-progress', (event, progress) => {
      console.log(`Received progress: ${progress.percent*100}%`);
      this.downloadProgress = Math.floor(progress.percent * 100);
    });
    // 打开下载目录监听器
    this.$ipc.on('folder-opened', (event, success) => {
      if (success) {
        this.$tools.alertMsg("文件夹已打开", "success");
      } else {
        this.$tools.alertMsg("打开文件夹失败", "error");
      }
    });
  }
}; 
</script>

<style lang="less" scoped>
// 图片选中样式
.icon-active{
  color: #1B89E6!important;
}
.shell{
  display: flex;
  height: calc(100vh - 72px);
  .sel-icon{
    margin-right: 6px;
    width: 13px;
    height: 13px;
    padding: 2px;
    color: #2D323B;
    background-color: #2D323B;
    border-radius: 2px;
  }
  .all-swit{
    position: relative;
  }
  .icon{
    width: 12px;
    height: 12px;
  }
  .right-folder{
    position: absolute;
    right: 10px;
  }
  // 左侧样式
  .left{
    position: relative;
    display: flex;
    flex-shrink: 0;
    flex-direction: column;
    background-color: #24282F;
    width: 250px;
    height: calc(100vh - 72px);
    .l-top{
      display: flex;
      align-items: center;
      box-sizing: border-box;
      height: 40px;
      width: 100%;
      background-color: #202022;
      padding: 4px 4px 7px 4px;
      .card{
        height: 32px;
        line-height: 32px;
        text-indent: 10px;
        font-size: 12px;
        text-align: left;
        border-radius: 2px;
        width: 100%;
        margin-right: 4px;
        background-color: #25272D;
        color: #8F8F8F;
        cursor: pointer;
        &:hover{
          background-color: #3E4047;
          color: #fff;
        }
      }
      .collect{
        width: 24px;
        height: 24px;
        padding: 4px;
        flex-shrink: 0;
        border-radius: 2px;
        background-color: #25272D;
        cursor: pointer;
        .col-icon{
          width: 24px;
          height: 24px;
          color: #4C4D50;
        }
        &:hover{
          background-color: #3E4047;
        }
        &:hover .col-icon{
          color: #fff;
        }
      }
    }
    .l-mid{
      background-color: #262B32;
      padding: 8px 6px 4px 6px;
      margin-right: 3px;
      z-index: 1;
      .sel{
        position: relative;
        .s-content{
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #24252A;
          color: #7B7C7E;
          font-size: 13px;
          padding: 6px 10px;
          border-radius: 2px;
          cursor: pointer;
          &:hover{
            background-color: #3E4047;
            color: #fff;
          }
        }
        .s-items{
          position: absolute;
          width: 100%;
          background-color: #3D4450;
          padding: 4px 0px;
          .s-item{
            padding: 6px 8px;
            display: flex;
            align-items: center;
            font-size: 13px;
            color: #DCDEDF;
            cursor: pointer;
            &:hover .sel-icon{
              background-color: #1E1F23;
              color: #1E1F23;
            }
          }
        }
      }
      .search{
        background-color: #262B32;
        display: flex;
        align-items: center;
        color: #fff;
        font-size: 13px;
        padding: 6px 0px;
        .icon{
          width: 18px;
          height: 18px;
          padding: 6px 8px;
          color: #7B7C7E;
          background-color: #222429;
          border-radius: 2px;
        }
        input{
          width: 100%;
          height: 30px;
          padding-right: 8px;
          color: #fff;
          background-color: #222429;
          border-radius: 2px;
        }
      }
    }
    .l-bot{
      margin-bottom: 40px;
      overflow: hidden auto;
      &::-webkit-scrollbar {
        display: none; /* Safari 和 Chrome隐藏滚动条 */
      }
      .all-swit{
        position: sticky;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px 16px;
        background: linear-gradient(to right,#292F3B,#24282F);
        color: #CAE4FB;
        font-size: 14px;
        cursor: pointer;
        .icon{
          width: 14px;
          height: 14px;
        }
        span{
          margin-left: 4px;
        }
      }
      .items{
        padding: 4px 0px;
        .s-item{
          cursor: pointer;
          display: flex;
          align-items: center;
          color: #fff;
          font-size: 14px;
          padding: 5px 26px;
          .icon{
            width: 15px;
            height: 15px;
            margin-right: 4px;
            flex-shrink: 0;
          }
          span{
            white-space: nowrap; /* 禁止换行 */
            overflow: hidden; /* 隐藏溢出部分 */
            text-overflow: ellipsis; /* 显示省略号 */
          }
          &:hover{
            background-color: #323A4B;
          }
        }
      }
    }
    .add-game{
      position: absolute;
      background-color: #171D25;
      box-sizing: border-box;
      border-top: 1px solid #303641;
      border-radius: 2px;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      text-align: left;
      bottom: 0;
      padding: 0px 20px;
      cursor: pointer;
      .icon{
        background-color: #67707B;
        width: 10px;
        height: 10px;
        padding: 3px;
        margin-right: 8px;
        color: #171D25;
      }
      span{
        font-size: 12px;
        color: #8B929A;
      }
      &:hover .icon{
        background-color: #FFFFFF;
      }
      &:hover span{
        color: #FFFFFF;
      }
    }
  }
  // 右侧样式
  .right{
    .all{
      position: relative;
      width: calc(100vw - 260px);
      background-color: #141414;
      background-size: cover;
      background-position: center;
      background-position-y: 80%;
      height: 45vh;
      .tit{
        position: absolute;
        bottom: 10px;
        left: 20px;
        font-size: 30px;
        font-weight: bold;
        background: linear-gradient(to right bottom, #000 50%, #2660dc 95%,#000);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
      }
    }
    .game{
      padding: 8px 20px;
      .g-top{
        width: 150px;
        display: flex;
        align-items: center;
        color: #f2f2f2;
        background: linear-gradient(to right bottom, #1A9FFF, #1CB24C);
        border-radius: 2px;
        .icon{
          width: 36px;
          height: 36px;
          padding: 7px;
          background: transparent;
        }
        button{
          width: 100px;
          height: 50px;
          font-size: 20px;
          background: transparent;
          text-align: left;
          color: #f2f2f2;
        }
      }
    }
  }
  // 弹窗样式
  .el-right{
    padding: 10px 15px;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    overflow: hidden auto;
    &::-webkit-scrollbar {
      display: none; /* Safari 和 Chrome隐藏滚动条 */
    }
    .el-item{
      margin: 4px 5px;
      background-color: #000;
      width: 190px;
      height: 280px;
      display: flex;
      justify-content: center;
      cursor: pointer;
      img{
        width: 190px;
        height: 280px;
        object-fit: cover;
        object-position: center;
      }
      span{
        font-size: 24px;
        color: #aaa;
        padding: 20px;
        word-break: break-all;
      }
      // dis
    }
  }
}
  // 下载进度弹窗样式
  .download-dialog-content {
    padding: 10px;
    
    .download-progress-text {
      text-align: center;
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: bold;
    }
    
    .download-progress-bar {
      height: 20px;
      background-color: #333;
      border-radius: 10px;
      overflow: hidden;
      margin-bottom: 15px;
      
      .download-progress-fill {
        height: 100%;
        background: linear-gradient(to right, #1A9FFF, #1CB24C);
        transition: width 0.3s ease;
      }
    }
  }
  
  // 自定义el-dialog样式
  :deep(.el-dialog) {
    background-color: #24282F;
    color: #fff;
    border-radius: 8px;
    
    .el-dialog__header {
      background-color: #171D25;
      padding: 15px 20px;
      margin-right: 0;
      border-bottom: 1px solid #303641;
      border-radius: 8px 8px 0 0;
    }
    
    .el-dialog__title {
      color: #fff;
      font-weight: bold;
    }
    
    .el-dialog__body {
      padding: 20px;
      color: #fff;
    }
    
    .el-dialog__footer {
      padding: 10px 20px 20px;
      border-top: 1px solid #303641;
    }
  }
</style>
